package com.fh.web.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
 * 资源文件读取工具类
 * 
 * @author Yubin
 *
 */
public class PropertiesReader {

	private static PropertiesReader reader = null;

	private Properties propsCode = null;

	public static final String DEFAULT_PROPERTIES_FILE = "/config.properties";
	
	private static Map<String, PropertiesReader> configMap = new HashMap<String, PropertiesReader>();
	/**
	 * 获得一个PropertiesReader实例
	 * 默认读取根目录下"/config.properties"配置
	 * @return
	 */
	public static PropertiesReader getInstance() {
		if(configMap.containsKey(DEFAULT_PROPERTIES_FILE) && null != configMap.get(DEFAULT_PROPERTIES_FILE)) {
			reader = configMap.get(DEFAULT_PROPERTIES_FILE);
		}else{
			reader = new PropertiesReader("");
			configMap.put(DEFAULT_PROPERTIES_FILE, reader);
		}
		return reader;
	}
	/**
	 * 获得一个PropertiesReader实例
	 * @param confFilePath 自定义全路径</br> 
	 * 		     例:"/config.properties"
	 * @return
	 */
	public static PropertiesReader getInstance(String confFilePath) {
		if(configMap.containsKey(confFilePath) && null != configMap.get(confFilePath)) {
			reader = configMap.get(confFilePath);
		}else{
			reader = new PropertiesReader(confFilePath);
			configMap.put(confFilePath, reader);
		}
		return reader;
	}
	
	/**
	 * 根据路径创建properties
	 * 
	 * @param path
	 * @return
	 */
	public PropertiesReader(String fileFullName) {
		propsCode = new Properties();
		InputStream is = null;
		try {
			if(StringUtil.isNull(fileFullName)){
				is = getClass().getResourceAsStream(DEFAULT_PROPERTIES_FILE);
			}else{
				is = getClass().getResourceAsStream(fileFullName);
			}
			
			if(is != null){
				BufferedReader bf = new BufferedReader(new InputStreamReader(is));  
				propsCode.load(bf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
					is = null;
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}
	
	/**
	 * 根据key读取value
	 * @param key
	 * @return
	 */
	public String getValue(Object key) {
		String value = "";
		try {
			if(key != null && !StringUtil.isFullNull(propsCode.getProperty(key.toString()))){
				value = propsCode.getProperty(key.toString());
			}
			return value;
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("ConfigInfoError" + e.toString());
			return null;
		}
	}
}
